<?php

declare(strict_types=1);

namespace app\service\order;

use app\model\Order;
use app\model\OrderItem;
use app\model\OrderRefund;
use app\model\OrgMember;
use app\service\notify\CreateNotifyService;
use app\util\GenNoUtil;
use InvalidArgumentException;
use think\facade\Db;
use think\Paginator;

class AfterSaleService
{
    public function __construct(private CreateNotifyService $notifyService)
    {
    }

    public function paginate(array $filters, int $page, int $pageSize): Paginator
    {
        $query = OrderRefund::with(['order', 'item'])->order('id', 'desc');
        $this->applyFilters($query, $filters);

        return $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);
    }

    public function paginateWithDetails(array $filters, int $page, int $pageSize): Paginator
    {
        $query = OrderRefund::with([
            'order' => static function ($orderQuery) {
                $orderQuery->with([
                    'items',
                    'buyer.profile',
                    'sellerOrg',
                    'assistUser.profile',
                ]);
            },
            'item',
        ])->order('id', 'desc');

        $this->applyFilters($query, $filters);

        return $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);
    }

    public function get(int $id, ?int $userId = null): OrderRefund
    {
        $refund = OrderRefund::with(['order', 'item'])->find($id);
        if (!$refund) {
            throw new InvalidArgumentException('退款单不存在');
        }

        if ($userId !== null) {
            $this->assertCanView($refund, $userId);
        }

        return $refund;
    }

    public function format(OrderRefund $refund): array
    {
        $refund->loadMissing([
            'order' => static function ($orderQuery) {
                $orderQuery->with([
                    'items',
                    'buyer.profile',
                    'sellerOrg',
                    'assistUser.profile',
                ]);
            },
            'item',
        ]);

        $data = [
            'id' => (int) $refund->id,
            'refund_no' => $refund->refund_no ?? '',
            'order_id' => (int) $refund->order_id,
            'order_item_id' => $refund->order_item_id ? (int) $refund->order_item_id : null,
            'status' => (int) $refund->status,
            'status_label' => OrderRefund::labelForStatus((int) $refund->status),
            'refund_type' => $refund->refund_type ?? '',
            'reason' => (string) ($refund->reason ?? ''),
            'evidence' => $this->formatMediaOutput($refund->evidence ?? []),
            'apply_amount' => (float) ($refund->apply_amount ?? 0),
            'approved_amount' => (float) ($refund->approved_amount ?? 0),
            'buyer_amount' => (float) ($refund->buyer_amount ?? 0),
            'seller_amount' => (float) ($refund->seller_amount ?? 0),
            'platform_amount' => (float) ($refund->platform_amount ?? 0),
            'applicant_id' => (int) ($refund->applicant_id ?? 0),
            'approver_id' => $refund->approver_id ? (int) $refund->approver_id : null,
            'remark' => (string) ($refund->remark ?? ''),
            'approve_time' => $refund->approve_time,
            'complete_time' => $refund->complete_time,
            'create_time' => $refund->create_time,
            'update_time' => $refund->update_time,
        ];

        if ($refund->order) {
            $data['order'] = $this->formatOrderSummary($refund->order);
        }

        if ($refund->item) {
            $data['item'] = $this->formatOrderItem($refund->item);
        }

        return $data;
    }

    public function formatCollection(iterable $refunds): array
    {
        $results = [];
        foreach ($refunds as $refund) {
            if ($refund instanceof OrderRefund) {
                $results[] = $this->format($refund);
            }
        }

        return $results;
    }

    public function getWithDetails(int $id): OrderRefund
    {
        $refund = OrderRefund::with([
            'order' => static function ($orderQuery) {
                $orderQuery->with([
                    'items',
                    'buyer.profile',
                    'sellerOrg',
                    'assistUser.profile',
                ]);
            },
            'item',
        ])->find($id);

        if (!$refund) {
            throw new InvalidArgumentException('退款单不存在');
        }

        return $refund;
    }

    public function apply(int $buyerId, array $payload): OrderRefund
    {
        $orderId = (int) ($payload['order_id'] ?? 0);
        if ($orderId <= 0) {
            throw new InvalidArgumentException('订单参数不正确');
        }

        /** @var Order|null $order */
        $order = Order::find($orderId);
        if (!$order) {
            throw new InvalidArgumentException('订单不存在');
        }

        if ((int) $order->buyer_user_id !== $buyerId) {
            throw new InvalidArgumentException('无权操作该订单');
        }

        $orderItemId = isset($payload['order_item_id']) ? (int) $payload['order_item_id'] : null;
        if ($orderItemId) {
            $itemExists = OrderItem::where('order_id', $orderId)
                ->where('id', $orderItemId)
                ->find();
            if (!$itemExists) {
                throw new InvalidArgumentException('订单明细不存在');
            }
        }

        $applyAmount = (float) ($payload['apply_amount'] ?? 0);
        if ($applyAmount <= 0 || $applyAmount > (float) $order->buyer_paid_amount) {
            throw new InvalidArgumentException('申请金额不合法');
        }

        $existing = OrderRefund::where('order_id', $orderId)
            ->when($orderItemId, static function ($q) use ($orderItemId) {
                $q->where('order_item_id', $orderItemId);
            })
            ->whereIn('status', [OrderRefund::STATUS_PENDING, OrderRefund::STATUS_APPROVED])
            ->find();

        if ($existing) {
            throw new InvalidArgumentException('已存在处理中的售后申请');
        }

        [$record, $orderSnapshot] = Db::transaction(function () use ($order, $orderItemId, $applyAmount, $payload, $buyerId) {
            /** @var Order|null $lockedOrder */
            $lockedOrder = Order::lock(true)->find((int) $order->id);
            if (!$lockedOrder) {
                throw new InvalidArgumentException('订单不存在');
            }

            $evidence = $this->normalizeMedia($payload['evidence'] ?? []);

            /** @var OrderRefund $refund */
            $refund = OrderRefund::create([
                'order_id' => $lockedOrder->id,
                'order_item_id' => $orderItemId,
                'refund_no' => GenNoUtil::refund(),
                'refund_type' => $payload['refund_type'] ?? 'partial',
                'reason' => (string) ($payload['reason'] ?? ''),
                'evidence' => $evidence === [] ? null : $evidence,
                'apply_amount' => $applyAmount,
                'approved_amount' => 0,
                'buyer_amount' => 0,
                'seller_amount' => 0,
                'platform_amount' => 0,
                'status' => OrderRefund::STATUS_PENDING,
                'applicant_id' => $buyerId,
                'remark' => (string) ($payload['remark'] ?? ''),
            ]);

            $lockedOrder = $this->refreshOrderRefundState($lockedOrder, true);

            return [
                OrderRefund::with(['order', 'item'])->find((int) $refund->id),
                $lockedOrder->refresh(),
            ];
        });

        $this->notifySellerOnApply($orderSnapshot, $record);

        return $record->refresh();
    }

    public function approve(int $id, int $userId, array $payload): OrderRefund
    {
        $refund = Db::transaction(function () use ($id, $userId, $payload) {
            /** @var OrderRefund|null $refund */
            $refund = OrderRefund::with(['order', 'item'])->lock(true)->find($id);
            if (!$refund) {
                throw new InvalidArgumentException('退款单不存在');
            }

            $order = $refund->order;
            if (!$order) {
                throw new InvalidArgumentException('关联订单不存在');
            }

            $this->assertCanHandle($order, $userId);

            if ((int) $refund->status !== OrderRefund::STATUS_PENDING) {
                throw new InvalidArgumentException('当前状态无法审批');
            }

            $amount = isset($payload['approved_amount']) ? (float) $payload['approved_amount'] : (float) $refund->apply_amount;
            $amount = round($amount, 2);
            if ($amount <= 0) {
                throw new InvalidArgumentException('审批金额必须大于0');
            }
            if ($amount - (float) $refund->apply_amount > 0.01) {
                throw new InvalidArgumentException('审批金额不能超过申请金额');
            }

            $available = $this->calculateAvailableBuyerRefund($order, (int) $refund->id);
            if ($amount - $available > 0.01) {
                throw new InvalidArgumentException('审批金额超过可退额度');
            }

            $refund->approved_amount = $amount;
            $refund->status = OrderRefund::STATUS_APPROVED;
            $refund->approver_id = $userId;
            $refund->approve_time = date('Y-m-d H:i:s');
            $refund->remark = (string) ($payload['remark'] ?? $refund->remark);
            $refund->save();

            $order = $this->refreshOrderRefundState($order, true);

            return OrderRefund::with(['order', 'item'])->find((int) $refund->id);
        });

        $this->notifyBuyer($refund, 'approved');

        return $refund->refresh();
    }

    public function reject(int $id, int $userId, array $payload): OrderRefund
    {
        $refund = Db::transaction(function () use ($id, $userId, $payload) {
            /** @var OrderRefund|null $refund */
            $refund = OrderRefund::with(['order', 'item'])->lock(true)->find($id);
            if (!$refund) {
                throw new InvalidArgumentException('退款单不存在');
            }

            $order = $refund->order;
            if (!$order) {
                throw new InvalidArgumentException('关联订单不存在');
            }

            $this->assertCanHandle($order, $userId);

            if ((int) $refund->status !== OrderRefund::STATUS_PENDING) {
                throw new InvalidArgumentException('当前状态无法驳回');
            }

            $refund->status = OrderRefund::STATUS_REJECTED;
            $refund->approver_id = $userId;
            $refund->approve_time = date('Y-m-d H:i:s');
            $refund->remark = (string) ($payload['remark'] ?? $refund->remark);
            $refund->save();

            $order = $this->refreshOrderRefundState($order, true);

            return OrderRefund::with(['order', 'item'])->find((int) $refund->id);
        });

        $this->notifyBuyer($refund, 'rejected');

        return $refund->refresh();
    }

    public function complete(int $id, int $userId, array $payload): OrderRefund
    {
        $refund = Db::transaction(function () use ($id, $userId, $payload) {
            /** @var OrderRefund|null $refund */
            $refund = OrderRefund::with(['order', 'item'])->lock(true)->find($id);
            if (!$refund) {
                throw new InvalidArgumentException('退款单不存在');
            }

            $order = $refund->order;
            if (!$order) {
                throw new InvalidArgumentException('关联订单不存在');
            }

            $this->assertCanHandle($order, $userId);

            if (!in_array((int) $refund->status, [OrderRefund::STATUS_APPROVED, OrderRefund::STATUS_PENDING], true)) {
                throw new InvalidArgumentException('当前状态无法完成退款');
            }

            $approvedBase = isset($payload['approved_amount'])
                ? (float) $payload['approved_amount']
                : (float) $refund->approved_amount;
            if ($approvedBase <= 0) {
                $approvedBase = (float) $refund->apply_amount;
            }
            $approvedBase = round($approvedBase, 2);

            $buyerAmount = array_key_exists('buyer_amount', $payload)
                ? (float) $payload['buyer_amount']
                : $approvedBase;
            $sellerAmount = isset($payload['seller_amount']) ? (float) $payload['seller_amount'] : 0.0;
            $platformAmount = isset($payload['platform_amount']) ? (float) $payload['platform_amount'] : 0.0;

            if ($buyerAmount < 0 || $sellerAmount < 0 || $platformAmount < 0) {
                throw new InvalidArgumentException('退款金额分配不合法');
            }

            $buyerAmount = round($buyerAmount, 2);
            $sellerAmount = round($sellerAmount, 2);
            $platformAmount = round($platformAmount, 2);

            $totalAllocation = round($buyerAmount + $sellerAmount + $platformAmount, 2);
            if ($totalAllocation <= 0) {
                throw new InvalidArgumentException('退款金额必须大于0');
            }

            if (abs($totalAllocation - $approvedBase) > 0.01) {
                throw new InvalidArgumentException('退款金额分配与批准金额不一致');
            }

            $available = $this->calculateAvailableBuyerRefund($order, (int) $refund->id);
            if ($approvedBase - $available > 0.01) {
                throw new InvalidArgumentException('退款金额超出可退额度');
            }

            if ((int) $refund->status === OrderRefund::STATUS_PENDING) {
                $refund->approver_id = $userId;
                $refund->approve_time = date('Y-m-d H:i:s');
            }

            $refund->approved_amount = $approvedBase;
            $refund->status = OrderRefund::STATUS_COMPLETED;
            $refund->buyer_amount = $buyerAmount;
            $refund->seller_amount = $sellerAmount;
            $refund->platform_amount = $platformAmount;
            $refund->complete_time = date('Y-m-d H:i:s');
            $refund->remark = (string) ($payload['remark'] ?? $refund->remark);
            $refund->save();

            if ($refund->order_item_id) {
                /** @var OrderItem|null $item */
                $item = OrderItem::lock(true)->find((int) $refund->order_item_id);
                if ($item && (int) $item->order_id === (int) $order->id) {
                    $item->refund_amount = round((float) $item->refund_amount + $buyerAmount, 2);
                    $item->save();
                }
            }

            $order = $this->refreshOrderRefundState($order, true);

            return OrderRefund::with(['order', 'item'])->find((int) $refund->id);
        });

        $this->notifyBuyer($refund, 'completed');

        return $refund->refresh();
    }

    private function applyFilters($query, array $filters): void
    {
        $status = $filters['status'] ?? $filters['refund_record_status'] ?? null;
        if ($status !== null && $status !== '') {
            $query->where('status', (int) $status);
        }

        $buyerId = $filters['buyer_id'] ?? $filters['buyer_user_id'] ?? null;
        if ($buyerId) {
            $query->where('applicant_id', (int) $buyerId);
        }

        $sellerId = $filters['seller_id'] ?? $filters['seller_user_id'] ?? null;
        if ($sellerId) {
            $query->whereHas('order', static function ($q) use ($sellerId) {
                $q->where('seller_user_id', (int) $sellerId);
            });
        }

        if (!empty($filters['assist_user_id'])) {
            $assistId = (int) $filters['assist_user_id'];
            $query->whereHas('order', static function ($q) use ($assistId) {
                $q->where('assist_user_id', $assistId);
            });
        }

        if (!empty($filters['buyer_org_id'])) {
            $buyerOrgId = (int) $filters['buyer_org_id'];
            $query->whereHas('order', static function ($q) use ($buyerOrgId) {
                $q->where('buyer_org_id', $buyerOrgId);
            });
        }

        if (!empty($filters['seller_org_id'])) {
            $sellerOrgId = (int) $filters['seller_org_id'];
            $query->whereHas('order', static function ($q) use ($sellerOrgId) {
                $q->where('seller_org_id', $sellerOrgId);
            });
        }

        if (array_key_exists('order_status', $filters) && $filters['order_status'] !== null && $filters['order_status'] !== '') {
            $orderStatus = (int) $filters['order_status'];
            $query->whereHas('order', static function ($q) use ($orderStatus) {
                $q->where('status', $orderStatus);
            });
        }

        $orderRefundStatus = $filters['order_refund_status'] ?? $filters['refund_status'] ?? null;
        if ($orderRefundStatus !== null && $orderRefundStatus !== '') {
            $statusValue = (int) $orderRefundStatus;
            $query->whereHas('order', static function ($q) use ($statusValue) {
                $q->where('refund_status', $statusValue);
            });
        }

        if (!empty($filters['keyword'])) {
            $keyword = trim((string) $filters['keyword']);
            $query->where(static function ($sub) use ($keyword) {
                $sub->whereLike('refund_no', '%' . $keyword . '%')
                    ->whereOr(static function ($nested) use ($keyword) {
                        $nested->whereHas('order', static function ($orderQuery) use ($keyword) {
                            $orderQuery->whereLike('order_no', '%' . $keyword . '%');
                        });
                    });
            });
        }

        $startTime = $filters['start_time'] ?? null;
        $endTime = $filters['end_time'] ?? null;
        if ($startTime && $endTime) {
            $query->whereBetweenTime('create_time', $startTime, $endTime);
        }
    }

    private function formatOrderSummary(Order $order): array
    {
        $order->loadMissing([
            'items',
            'buyer.profile',
            'sellerOrg',
            'assistUser.profile',
        ]);

        $buyerName = '';
        $buyerPhone = '';
        if ($order->buyer) {
            $buyerPhone = $order->buyer->phone ?? '';
            $buyerName = $order->buyer->profile->real_name
                ?? $order->buyer->nickname
                ?? $buyerPhone;
        }

        $sellerName = $order->sellerOrg ? (string) $order->sellerOrg->name : '';

        $assistUser = null;
        if ($order->assist_user_id) {
            $assistName = '';
            if ($order->assistUser) {
                $assistName = $order->assistUser->profile->real_name
                    ?? $order->assistUser->nickname
                    ?? $order->assistUser->phone
                    ?? '';
            }
            $assistUser = [
                'id' => (int) $order->assist_user_id,
                'name' => $assistName,
            ];
        }

        $items = [];
        if ($order->items) {
            foreach ($order->items as $item) {
                if ($item instanceof OrderItem) {
                    $items[] = $this->formatOrderItem($item);
                }
            }
        }

        return [
            'id' => (int) $order->id,
            'order_no' => $order->order_no ?? '',
            'status' => (int) $order->status,
            'status_label' => $order->status_label,
            'refund_status' => (int) $order->refund_status,
            'pay_status' => (int) $order->pay_status,
            'ship_status' => (int) $order->ship_status,
            'source_channel' => $order->source_channel ?? '',
            'buyer_paid_amount' => (float) ($order->buyer_paid_amount ?? 0),
            'platform_commission_amount' => (float) ($order->platform_commission_amount ?? 0),
            'buyer' => [
                'id' => (int) $order->buyer_user_id,
                'org_id' => $order->buyer_org_id ? (int) $order->buyer_org_id : null,
                'name' => $buyerName,
                'phone' => $buyerPhone,
            ],
            'seller' => [
                'id' => $order->seller_user_id ? (int) $order->seller_user_id : null,
                'org_id' => (int) $order->seller_org_id,
                'name' => $sellerName,
            ],
            'assist_user' => $assistUser,
            'create_time' => $order->create_time,
            'paid_at' => $order->paid_at,
            'finished_at' => $order->finished_at,
            'amount_snapshot' => $order->amount_snapshot ?? [],
            'items' => $items,
        ];
    }

    private function formatOrderItem(OrderItem $item): array
    {
        return [
            'id' => (int) $item->id,
            'product_id' => (int) $item->product_id,
            'sku_id' => $item->sku_id ? (int) $item->sku_id : null,
            'quantity' => (int) $item->quantity,
            'unit_price' => (float) ($item->unit_price ?? 0),
            'subtotal' => (float) ($item->subtotal_amount ?? $item->unit_price * $item->quantity),
            'refund_amount' => (float) ($item->refund_amount ?? 0),
            'product_snapshot' => $item->product_snapshot ?? [],
        ];
    }

    private function formatMediaOutput($media): array
    {
        if (!$media) {
            return [];
        }

        if (is_string($media)) {
            return [$media];
        }

        if (!is_array($media)) {
            return [];
        }

        $result = [];
        foreach ($media as $item) {
            if (is_string($item)) {
                $trimmed = trim($item);
                if ($trimmed !== '') {
                    $result[] = $trimmed;
                }
            } elseif (is_array($item)) {
                $result = array_merge($result, $this->formatMediaOutput($item));
            }
        }

        return array_values(array_unique($result));
    }

    private function assertCanHandle(Order $order, int $userId): void
    {
        if ((int) $order->assist_user_id === $userId) {
            return;
        }

        if ((int) $order->seller_user_id === $userId) {
            return;
        }

        $ownerIds = OrgMember::where('org_id', (int) $order->seller_org_id)
            ->whereIn('role', [OrgMember::ROLE_OWNER, OrgMember::ROLE_ADMIN])
            ->column('user_id');

        if (in_array($userId, $ownerIds, true)) {
            return;
        }

        throw new InvalidArgumentException('无权处理该退款单');
    }

    private function assertCanView(OrderRefund $refund, int $userId): void
    {
        if ((int) $refund->applicant_id === $userId) {
            return;
        }

        $order = $refund->order ?: Order::find((int) $refund->order_id);
        if (!$order) {
            throw new InvalidArgumentException('关联订单不存在');
        }

        if ((int) $order->seller_user_id === $userId) {
            return;
        }

        if ((int) $order->assist_user_id === $userId) {
            return;
        }

        $ownerIds = OrgMember::where('org_id', (int) $order->seller_org_id)
            ->whereIn('role', [OrgMember::ROLE_OWNER, OrgMember::ROLE_ADMIN])
            ->column('user_id');

        if (in_array($userId, $ownerIds, true)) {
            return;
        }

        throw new InvalidArgumentException('无权查看该退款单');
    }

    private function refreshOrderRefundState(Order $order, bool $locked = false): Order
    {
        if (!$locked) {
            /** @var Order|null $fresh */
            $fresh = Order::lock(true)->find((int) $order->id);
            if ($fresh) {
                $order = $fresh;
            }
        }

        $refunds = OrderRefund::where('order_id', (int) $order->id)->select();

        $activeCount = 0;
        $completedCount = 0;
        $buyerTotal = 0.0;
        $sellerTotal = 0.0;
        $platformTotal = 0.0;

        foreach ($refunds as $item) {
            $status = (int) $item->status;
            if (in_array($status, [OrderRefund::STATUS_PENDING, OrderRefund::STATUS_APPROVED], true)) {
                $activeCount++;
            }
            if ($status === OrderRefund::STATUS_COMPLETED) {
                $completedCount++;
                $buyerTotal += (float) $item->buyer_amount;
                $sellerTotal += (float) $item->seller_amount;
                $platformTotal += (float) $item->platform_amount;
            }
        }

        $snapshot = $order->amount_snapshot ?? [];
        if (!is_array($snapshot)) {
            $snapshot = [];
        }

        $refundSnapshot = $snapshot['refunds'] ?? [];
        $originalPaid = isset($refundSnapshot['original_buyer_paid'])
            ? (float) $refundSnapshot['original_buyer_paid']
            : (float) $order->buyer_paid_amount;

        $snapshot['refunds'] = [
            'original_buyer_paid' => round($originalPaid, 2),
            'buyer_total' => round($buyerTotal, 2),
            'seller_total' => round($sellerTotal, 2),
            'platform_total' => round($platformTotal, 2),
            'net_buyer_paid' => round(max($originalPaid - $buyerTotal, 0), 2),
            'count' => count($refunds),
            'active_count' => $activeCount,
            'completed_count' => $completedCount,
            'updated_at' => date('Y-m-d H:i:s'),
        ];

        $order->amount_snapshot = $snapshot;

        if ($activeCount > 0) {
            $order->refund_status = Order::REFUND_STATUS_PROCESSING;
            $order->status = max((int) $order->status, Order::STATUS_AFTER_SALE);
        } elseif ($completedCount > 0) {
            $order->refund_status = Order::REFUND_STATUS_DONE;
            if ((int) $order->status === Order::STATUS_AFTER_SALE) {
                $order->status = Order::STATUS_COMPLETED;
            }
        } else {
            $order->refund_status = Order::REFUND_STATUS_NONE;
            if ((int) $order->status === Order::STATUS_AFTER_SALE) {
                $order->status = Order::STATUS_COMPLETED;
            }
        }

        $order->save();

        return $order;
    }

    private function calculateAvailableBuyerRefund(Order $order, ?int $excludeRefundId = null): float
    {
        $basePaid = $order->amount_snapshot['refunds']['original_buyer_paid'] ?? (float) $order->buyer_paid_amount;

        $reserved = 0.0;

        $query = OrderRefund::where('order_id', (int) $order->id);
        if ($excludeRefundId) {
            $query->where('id', '<>', $excludeRefundId);
        }

        foreach ($query->select() as $item) {
            $status = (int) $item->status;
            if ($status === OrderRefund::STATUS_COMPLETED) {
                $reserved += (float) $item->buyer_amount;
            } elseif ($status === OrderRefund::STATUS_APPROVED) {
                $reserved += (float) $item->approved_amount;
            }
        }

        $available = round($basePaid - $reserved, 2);

        return $available > 0 ? $available : 0.0;
    }

    private function notifySellerOnApply(Order $order, OrderRefund $refund): void
    {
        $targets = [];
        if ($order->seller_user_id) {
            $targets[] = [
                'id' => (int) $order->seller_user_id,
                'type' => 'seller',
            ];
        }

        if ($order->assist_user_id) {
            $targets[] = [
                'id' => (int) $order->assist_user_id,
                'type' => 'assistant',
            ];
        }

        if ($targets === []) {
            return;
        }

        $this->notifyService->add($targets, 'refund_apply', [
            'order_no' => $order->order_no,
            'refund_no' => $refund->refund_no,
            'apply_amount' => $refund->apply_amount,
        ]);
    }

    private function notifyBuyer(OrderRefund $refund, string $result): void
    {
        $order = $refund->order;
        $targets = [
            [
                'id' => (int) $refund->applicant_id,
                'type' => 'buyer',
            ],
        ];

        $this->notifyService->add($targets, 'refund_processed', [
            'order_no' => $order->order_no,
            'refund_no' => $refund->refund_no,
            'status' => $result,
        ]);
    }

    private function normalizeMedia($media): array
    {
        if (empty($media)) {
            return [];
        }

        if (!is_array($media)) {
            return [$media];
        }

        return array_values(array_filter($media, static fn($item) => $item !== null && $item !== ''));
    }
}
